<template>
<!-- E店宝订单录入 -->
  <div class="m-add-order">
    <!-- 商品列表 -->
    <div class="goods-list">
      <!-- 搜索条件 -->
      <div class="search">
        <!-- <div class="s-input">
          <w-input holder="请输入商品名称关键字" v-model="searchParams.name"></w-input>
        </div> -->
        <div class="s-input select-i">
          <!-- <w-select :options="storeList" v-model="searchParams.storeId"></w-select> -->
          <w-input value='好下单E店宝' disabled></w-input>
        </div>
        <!-- <w-button type="main" :disabled="!searchParams.storeId" @on-click="onSearchGoods">搜索</w-button> -->
      </div>

      <!-- 商品列表 -->
      <div class="list over-y" v-show="goodsList.recordList && goodsList.recordList.length">
        <div class="list-item" v-for="(goodsInfo, index) in goodsList.recordList" :key="index" :class="{'last-child': lastChild(goodsList.recordList.length, index)}">
          <div class="checkbox">
            <w-checkbox :label="`goods${index}`" :disabled="goodsInfo.disabled" v-model="goodsInfo.checked" @on-change="_selectedGoods(goodsInfo.checked, goodsInfo.id)"></w-checkbox>
          </div>
          <div class="goods clearfix">
            <div class="goods-img fl" v-lazy:background-image="goodsInfo.goodsImg"></div>
            <div class="goods-info fr">
              <p>{{goodsInfo.goodsName}} {{goodsInfo.goodsSerial}}</p>
              <!-- 价格区间 -->
              <div class="price-lot">
                <!-- 价格 -->
                <div>
                  <div class="col-xs-12 col-sm-12 col-md-12 line1">
                    <span class="title">单价：</span>
                    <span class="c-main p-item" v-for="(price, pIndex) in goodsInfo.tierdPrice" :key="pIndex">￥<span class="price">{{price.price | currency}}</span></span>
                  </div>
                </div>
                <!-- 批量 -->
                <div>
                  <div class="col-xs-12 col-sm-12 col-md-12 line1">
                    <span class="title">起订量：</span>
                    <span class="lot" v-for="(treid, pIndex) in goodsInfo.tierdPrice" :key="pIndex" v-html="treidCount(treid, index)"></span>
                  </div>
                </div>
              </div>
              <!-- 商品sku -->
              <div class="goods-sku">
                <goods-sku 
                  :curIndex="index"
                  :tired-price="goodsInfo.curPrice"
                  :tireds="goodsInfo.tierdPrice"
                  :checked="goodsInfo.checked"
                  :goodsid="goodsInfo.id"
                  :sku-list="goodsInfo.skuList"
                  @selected-skus="selectSkuList" 
                  @change-image="changeSkuImage" 
                  @clear-error-color="errorColor={}"></goods-sku>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 没有数据 -->
      <div class="list" v-if="!goodsList.recordList || !goodsList.recordList.length">
        <p class="empty">亲，木有数据哦~~</p>
      </div>

      <!-- 分页 -->
      <!-- <div class="page clearfix" v-if="goodsList.pageCount > 1">
        <div class="fr">
          <w-paging :total="goodsList.pageCount" :current="goodsList.currentPage" @on-page="onChangePage"></w-paging>
        </div>
      </div> -->

      <!-- 总计 -->
      <div class="search m-all" v-if="goodsList.recordList && goodsList.recordList.length">
        <div>
          共计 {{allCount}} 件 货品金额：<span class="c-main">{{allGoodsPrice | currency}} 元</span>
        </div>
      </div>
    </div>

    <!-- 订单基本信息 -->
    <w-form-validate @on-validate="onValidate" v-show="goodsList.recordList && goodsList.recordList.length">
      <div class="m-order-info clearfix">
        <div class="fl">
          <div class="order-item">
            <span class="title">收货人</span>
            <div class="order-input">
              <w-input holder="请输入" rule="isEmpty" error="请输入收货人" v-model="addParams.receiverName"></w-input>
            </div>
          </div>
          <div class="order-item">
            <span class="title" style="vertical-align: top;margin-top: 8px;">收货地址</span>
            <div class="order-input area">
              <w-area-picker v-model="addParams.receiverArea"></w-area-picker>
            </div>
          </div>
          <div class="order-item">
            <span class="title">运费</span>
            <div class="order-input">
              <w-input holder="请输入" rule="isMoney" error="格式错误" v-model="addParams.shipPrice"></w-input>
            </div>
            元
          </div>
          <div class="order-item">
            <span class="title">下单时间</span>
            <div class="order-input">
              <w-input placeholder="请选择" id="addtime" v-model="addParams.addtime"></w-input>
            </div>
          </div>
          <div class="order-item">
            <span class="title">发货时间</span>
            <div class="order-input">
              <w-input placeholder="请选择" id="shipTime" v-model="addParams.shipTime"></w-input>
            </div>
          </div>
          <div class="order-item">
            <span class="title">物流名称</span>
            <div class="order-input">
              <w-input holder="请输入" v-model="addParams.expressName"></w-input>
            </div>
          </div>
          <!-- <div class="order-item">
            <span class="title">付款方式</span>
            <div class="order-input">
              <w-select :options="paymentoptions" v-model="addParams.paymentName"></w-select>
            </div>
          </div> -->
        </div>
        <div class="fr">
          <div class="order-item">
            <span class="title">收货人号码</span>
            <div class="order-input">
              <w-input holder="请输入" rule="isEmpty|isMobile" error="请输入手机号|格式错误" v-model="addParams.receiverMobile"></w-input>
            </div>
          </div>
          <div class="order-item">
            <span class="title">详细地址</span>
            <div class="order-input">
              <w-input holder="请输入" rule="isEmpty" error="请输入详细地址" v-model="addParams.receiverAreaInfo"></w-input>
            </div>
          </div>
          <div class="order-item">
            <span class="title">订单类型</span>
            <div class="order-input">
              <w-select :options="orderTypeOptions" v-model="addParams.orderType"></w-select>
            </div>
          </div>
          <div class="order-item">
            <span class="title">付款时间</span>
            <div class="order-input" >
              <w-input placeholder="请选择" id="payTime" v-model="addParams.payTime"></w-input>
            </div>
          </div>
          <div class="order-item">
            <span class="title">完成时间</span>
            <div class="order-input">
              <w-input placeholder="请选择" id="confirmTime" v-model="addParams.confirmTime"></w-input>
            </div>
          </div>
          <div class="order-item">
            <span class="title">快递单号</span>
            <div class="order-input">
              <w-input holder="请输入" rule="isShipCode" error="格式错误" v-model="addParams.shipCode"></w-input>
            </div>
          </div>
        </div>
      </div>
      <div class="btns-group">
        <button type="submit" class="btn">提交</button>
        <button class="btn colse" @click="_cancelParams">取消</button>
      </div>
    </w-form-validate>
  </div>
</template>

<script>
import GoodsSku from './components/GoodsSkuOrder'
import { apiShopMange, apiOrderMange } from 'js/api'
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      skuImage: '', // 主图
      // 支付方式
      paymentoptions: [
        {
          'label': '中金银联',
          'value': 'zj_yl'
        },
        {
          'label': '中金扫码',
          'value': 'zj_sm'
        },
        {
          'label': '中金快捷',
          'value': 'zj_kj'
        },
        {
          'label': '农商行支付',
          'value': 'rcb_pay'
        }
      ],
      // 订单类型
      orderTypeOptions: [
        {
          'label': 'PC网页订单',
          'value': 'web'
        },
        {
          'label': '手机网页订单',
          'value': 'h5'
        },
        {
          'label': 'android手机客户端',
          'value': 'android'
        },
        {
          'label': 'ios手机客户端',
          'value': 'ios'
        }
      ],
      storeList: [], // 店铺列表
      // 搜索商品入参
      searchParams: {
        accessToken: this.$store.getters.token,
        threeMenuCode: this.$route.query.three || '',
        name: '',
        storeId: ''
        // currentPage: 1,
        // showCount: 10
      },
      goodsList: {},
      selectedSkus: [],
      // 当前总数量
      allCount: 0,
      // 总计价格
      allGoodsPrice: 0,
      // 订单新增入参
      addParams: {
        accessToken: this.$store.getters.token,
        threeMenuCode: this.$route.query.three || '',
        addtime: '',
        shipTime: '', // 发货时间
        confirmTime: '', // 收货时间
        paymentName: '',
        expressName: '', // 物流名称
        shipCode: '', // 发货单号
        receiverArea: '',
        receiverAreaInfo: '',
        receiverMobile: '',
        receiverName: '',
        orderType: '',
        shipPrice: 0,
        payTime: '',
        storeVoList: [
          {
            storeId: '',
            goodsList: []
          }
        ]
      },
      checkedGoods: []
    }
  },
  mounted() {
    // 时间控件更改，获取具体的年月日时分秒
    this.$nextTick(() => {
      this._selectDate('addtime')
      this._selectDate('payTime')
      this._selectDate('shipTime')
      this._selectDate('confirmTime')
    })
  },
  computed: {
    ...mapGetters(['token'])
  },
  created() {
    if (!this.token) return
    // 获取所有营业中的店铺列表
    apiShopMange.apiShopName(this.token, '好下单E店宝').then(data => {
      this.searchParams.storeId = data.data[0].id
      this.onSearchGoods()
      // this.storeList = data.data || []
      // if (!this.storeList || this.storeList.length) {
      //   this.storeList = this.storeList.map(item => {
      //     return {
      //       label: item.company,
      //       value: item.id
      //     }
      //   })

      //   // 默认第一个商家 
      //   this.searchParams.storeId = this.storeList[0].value
      //   this.onSearchGoods()
      // }
    })
  },
  methods: {
    _selectDate(label) {
      jeDate(`#${label} input`, {
        theme: {
          bgcolor: '#f00385',
          color: '#ffffff',
          pnColor: '#00CCFF'
        },
        format: 'YYYY-MM-DD hh:mm:ss',
        minDate: '1900-01-01',
        maxDate: '2099-12-31',
        onClose: false,
        // 清空 回调
        clearfun: (elem, val) => {
          this.addParams[label] = ''
        },
        // 点确定 回调
        donefun: obj => {
          this.addParams[label] = obj.val
        }
      })
    },
    /**
     * 获取商品列表
     */
    onSearchGoods() {
      this.selectedSkus = []
      this.goodsList = [] // 防止切换分页产生脏数据
      apiOrderMange.apiGoodsList(this.searchParams).then(data => {
        this.goodsList = data.data || {}
        if (!this.goodsList || this.goodsList.totalCount == 0) return
        this.goodsList.recordList.forEach(v => {
          this.$set(v, 'checked', false)
          this.$set(v, 'goodsImg', v.mainPhotoPath)
          this.$set(v, 'disabled', true) // 商品是否可以选中
          this.$set(v, 'curPrice', v.tierdPrice[0].price) // 默认当前阶梯价为第一个阶梯价格
          this.$set(v, 'goodsPrice', 0) // 当前某商品价格
        })
      })
    },
    /**
     * 分页
     */
    // onChangePage(page) {
    //   this.searchParams.currentPage = page
    //   this.onSearchGoods()
    // },
    /**
     * 起订量
     * @param  { Number } count 当前的值
     * @param  { Number } index 第几个
     */
    treidCount(tierdPrice, index) {
      // 如果小于起订量
      if (index < tierdPrice.length - 1) {
        return `${tierdPrice.count}件`
      }
      return `&ge;${tierdPrice.count.split('-')[0] || 0}件`
    },
    // 样式
    lastChild(length, curIndex) {
      if (length%2 != 0 && length > 0) {
        if (length - 2 == curIndex) {
          return true
        }
      }
      return false
    },
    /**
     * 改变sku中的商品图片
     *
     * @param { String } imgPath sku中附带的商品图片
     */
    changeSkuImage(imgPath) {
      // 商品图片不存在，则不操作
      if (!imgPath.img) {
        return
      }
      this.goodsImg = this.goodsList.recordList.forEach((v, index) => {
        if (index == imgPath.cur) {
          v.goodsImg = imgPath.img
        }
      })
    },
    /**
     * 将选中的sku保存到全局作用域中
     *
     * @param  { Array } data 在sku组件中点击sku列表
     */
    selectSkuList(data) {
      // 总数量
      let totalCount = 0

      // 当前阶梯价，默认第一个
      let curTiredPrice = data.tireds[0].price

      // 便利数据，累加单个商品总数量数量
      data.list.forEach((v) => {
        if (v.specpropertyList && v.specpropertyList.length > 0) {
          v.specpropertyList.forEach((v1) => {
            if (v1.number) {
              totalCount += v1.number
            }
          })
        }
      })

      // 当前阶梯价
      data.tireds.forEach((v, index) => {
        // 区间价格的开始数量
        let startNumber = 0

        // 区间价格的结束数量
        let endNumber = 0

        // 取出阶梯价区间值，将价格累加区间值
        if (v && v.count) {
          startNumber = Number(v.count.split('-')[0])
          endNumber = Number(v.count.split('-')[1])

          // 如果在区间之间，则累加价格
          if (startNumber <= totalCount && (endNumber >= totalCount || isNaN(endNumber))) {
            curTiredPrice = v.price
          }
        }
      }) 

      // 最低起订量
      const minCount = Number(data.tireds[0].count.split('-')[0])

      // 如果总数量是0，则不追加（第一次点击）
      if (this.selectedSkus.length == 0 && totalCount == 0) {
        return
      }
      
      // 选中的sku
      this.selectedSkus.push(data)

      // 根据sku的数量，判断该商品是否可以选中
      this.goodsList.recordList.forEach(v => {
        if (v.id == data.goodsId) {
          // 低于最低起订量，不可选中,若已选择，则清空选择项
          if (minCount > totalCount) {
            v.disabled = true
            v.checked = false
          } else {
            v.disabled = false
          }
          
          // 若sku数量>0时，该商品可以选中且显示当前的阶梯价
          if (totalCount > 0) {
            // v.disabled = false
            v.curPrice = curTiredPrice
          }

          // 将该商品的选中状态记录
          data.checked = v.checked

          // 当前商品的价格=当前阶梯价*数量
          v.goodsPrice = Number(curTiredPrice * totalCount)

          // 判断已选中的商品，需累加数量
          this._selectedGoods(v.checked, data.goodsId)
        }
      })
    },
    /**
     * 已选中商品时，计算总计的数量以及总计的价格
     */
    _selectedGoods(bool, goodsid) {
      const selectedGoodsList = this._uniqueArray(this.selectedSkus)
      // 循环数组，获取当前商品的选中状态
      selectedGoodsList.forEach(v => {
        if (v.goodsId == goodsid) {
          v.checked = bool
        }
      })
      this.__calcuTotalCount()
      this.__calcuTotalPrice()
    },
    /**
    * 计算总数量
     */
    __calcuTotalCount() {
      this.allCount = 0
      const selectedGoodsList = this._uniqueArray(this.selectedSkus)

      // 循环数组，获取当前选中的商品总数量
      selectedGoodsList.forEach(v => {
        if (!v.checked) return
        v.list.forEach(goods => {
          if (goods.specpropertyList && goods.specpropertyList.length) {
            goods.specpropertyList.forEach(sku => {
              if (sku.number) {
                this.allCount += sku.number
              }
            })
          }
        })
      })
      
      this.__calcuTotalPrice()
    },
    /**
     * 计算总价格
     */
    __calcuTotalPrice() {
      // 总价格
      this.allGoodsPrice = 0

      this.goodsList.recordList.forEach(v => {
        if (v.checked) {
          this.allGoodsPrice += v.goodsPrice
        }
      })
    },
    /**
     * json数组去重
     */
    _uniqueArray(array) {
      if (!array || array.length == 0) return
      var result = []
      for (var i = 0; i < array.length; i++) {
        var item = array[i]
        var repeat = false
        for (var j = 0; j < result.length; j++) {
          if (item.goodsId == result[j].goodsId) {
            repeat = true
            break
          }
        }
        if (!repeat) {
          result.push(item)
        }
      }
      return result
    },
    /**
     * 规范提交订单的入参
     */
    _validateParams() {
      const selectedList = this.addParams.storeVoList[0].goodsList
      let selectedGoods = []
      this.addParams.storeVoList[0].storeId = this.searchParams.storeId
      selectedGoods = this._uniqueArray(this.selectedSkus)
      // 遍历已选中且sku中有数量sku
      this.checkedGoods.forEach(checked => {
        selectedGoods.forEach(goods => {
          if (Number(checked.goodsId) == Number(goods.goodsId)) {
            let gsp = []
            goods.list.forEach((v, index) => {
              if (v.specpropertyList && v.specpropertyList.length > 0) {
                v.specpropertyList.forEach((v1) => {
                  // 将选择了数量的sku加上去
                  if (v1.number > 0 && Number(checked.goodsId) == Number(goods.goodsId)) {
                    gsp.push({
                      cartGsp: [v.specpropertyId, v1.specpropertyId].join(','),
                      goodsSpecName: ['顔色', '尺码'],
                      goodsSpecContent: [v.specpropertyName, v1.specpropertyName],
                      count: v1.number
                    })
                  }
                })
              }
            })
            selectedList.push({
              goodsId: goods.goodsId,
              goodsGsp: gsp
            })
          }
        })
      })
      return this.addParams
    },
    /**
     * 将时间的标准格式转换成时间戳
     */
    _timeFormate(date) {
      if (!date) return
      return new Date(date).getTime()
    },
    /**
     * 比较时间戳的大小，决定可选时间的最大值
     */
    _compareTimeout(maxTime) {
      if (!maxTime) return '3016-01-01'
      return maxTime
    },
    /**
     * 提交订单
     */
    onValidate() {
      let selectedLen = 0
      
      if (!this.addParams.receiverArea) {
        this.$toast('请选择收货地址')
        return
      }
      if (!this.addParams.orderType) {
        this.$toast('请选择订单类型')
        return
      }
      if (!this.addParams.addtime) {
        this.$toast('请选择下单时间')
        return
      }
      if (!this.addParams.payTime) {
        this.$toast('请选择付款时间')
        return
      }
      // if (this._timeFormate(this.addParams.addtime) > this._timeFormate(this.addParams.payTime)) {
      //   this.$toast('下单时间应小于付款时间')
      //   return
      // }
      if (!this.addParams.shipTime) {
        this.$toast('请选择发货时间')
        return
      }
      if (!this.addParams.confirmTime) {
        this.$toast('请选择完成时间')
        return
      }
      if (this._timeFormate(this.addParams.addtime) > (this._timeFormate(this.addParams.payTime) || this._timeFormate(this.addParams.shipTime) || this._timeFormate(this.addParams.confirmTime))) {
        this.$toast('下单时间应小于付款时间,发货时间和完成时间')
        return
      }
      if (this._timeFormate(this.addParams.payTime) < this._timeFormate(this.addParams.addtime) || (this._timeFormate(this.addParams.payTime) > (this._timeFormate(this.addParams.confirmTime) || this._timeFormate(this.addParams.shipTime)))) {
        this.$toast('付款时间应大于等于下单时间且不大于完成时间和发货时间')
        return
      }
      if (this._timeFormate(this.addParams.shipTime) > this._timeFormate(this.addParams.confirmTime) || this._timeFormate(this.addParams.shipTime) < (this._timeFormate(this.addParams.addtime) || this._timeFormate(this.addParams.payTime))) {
        this.$toast('发货时间应大于下单时间和付款时间，且小于完成时间')
        return
      }
      if (this._timeFormate(this.addParams.confirmTime) < (this._timeFormate(this.addParams.payTime) || this._timeFormate(this.addParams.addtime) || this._timeFormate(this.addParams.shipTime))) {
        this.$toast('完成时间应大于下单时间和付款时间,发货时间')
        return
      }
      // if (!this.addParams.paymentName) {
      //   this.$toast('请选择付款方式')
      //   return
      // }

      this.goodsList.recordList.forEach(v => {
        if (v.checked) {
          this.checkedGoods.push({'goodsId': v.id}) // 已选中的商品
          selectedLen += 1
        }
      })
      if (!selectedLen) {
        this.$toast('请选择需要下订单的商品')
        return
      }

      // 校验入参格式规范
      this._validateParams()
      
      if (!this.addParams.shipPrice) {
        this.addParams.shipPrice = 0
      }

      apiOrderMange.apiEStroeOrder(this.addParams).then(data => {
        this.$toast('已生成订单', () => {
          // this.$router.go(0)
        })
      })
    },
    /**
     * 取消新增订单操作时，清空入参
     */
    _cancelParams() {
      let _this = this
      this.$modal({
        title: '提示',
        content: '确认取消该订单信息？',
        onConfirm() {
          _this.$router.go(0)
        }
      })
    }
  },
  components: {
    'goods-sku': GoodsSku
  }
}
</script>

<style lang="scss">
.m-add-order {
  .m-paging button {
    width: 30px;
    height: 30px;
  }
  .btns-group {
    .btn {
      width: 140px;
    }
    .option {
      margin-left: 40px;
    }
  }
  .order-item {
    .areapicker-wrap .select-wrap {
      width: 140px;
      margin-right: 8px;
      &:last-child {
        margin-right: 0
      }
    }
    .area {
      .select-wrap .form-control {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
  .list-item {
    .m-checkbox .check-btn {
      width: 18px;
      height: 18px;
      margin-left: -4px;
    }
  }
}
</style>

<style lang="scss" scoped>
.m-add-order {
  .goods-list {
    border:1px solid rgba(219,219,219,1);
  }
  .search {
    width:100%;
    height:40px;
    background:rgba(242,242,242,1);
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding-right: 20px;
  }
  .s-input {
    width: 200px;
    display: inline-block;
    margin-right: 20px
  }
  .select-i {
    min-width: 200px;
    width: auto;
  }
  .m-all {
    border-top:1px solid rgba(219,219,219,1);
    background-color: #ffffff;
  }
  .over-y {
    max-height: 874px;
    overflow-y: scroll;
  }
}
.list-item {
  // width: 594px;
  width: 585px;
  border: 1px solid #DBDBDB;
  border-bottom: none;
  border-left: none;
  display: inline-block;
  padding: 12px;
  vertical-align: text-top;
  & > div {
    display: inline-block
  }
  &:nth-child(2n) {
    border-right: none
  }
  .checkbox {
    vertical-align: top;
  }
  .goods {
    .goods-img {
      width: 208px;
      height: 208px;
      margin-right: 16px;
      display: inline-block;
      background-size: contain;
      background-repeat: no-repeat;
    }
    .goods-info {
      width: 312px;
      display: inline-block;
      font-size: 12px;
    }
    p {
      line-height: 22px;
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-bottom: 5px;
    }
    .price-lot {
      background-color: #efefef;
      color: #404040;
      font-size: 12px;
      
      & > div {
        height: 30px;
        line-height: 30px;
      }
    }
    .title {
      color: #AAAAAA;
      display: inline-block;
      margin-left: 10px;
      width: 50px;
    }
    .p-item {
      width: 25%;
      display: inline-block;
      text-align: left;
    }
    .price {
      font-size: 16px;
      font-weight: 600;
    }
    .lot {
      display: inline-block;
      min-width: 25%;
      text-align: left;
    }
  }
}
.empty {
  text-align: center;
  margin: 30px;
}
.last-child {
  border-bottom: 1px solid #dbdbdb
}
.goods-sku {
  margin-top: 10px;
}
.page {
  position: relative;
  background-color: #F2F2F2;
  padding: 10px 20px 10px;
}
.m-order-info {
  .order-item {
    margin-top: 20px;
    .title {
      font-size: 12px;
      display: inline-block;
      width: 70px;
      text-align: right;
    }
    .order-input {
      width: 448px;
      display: inline-block;
      margin-left: 10px;
    }
  }
}
.btns-group {
  text-align: center;
  margin: 30px auto 200px;
}
</style>
